package com.j.Collection.Set;

import java.util.HashSet;
/**
 * 关于HashSet中add()方法的实现方式
 * 以下对于源码的覆盖，让其对象内容相同时判断为同一对象不能都够被添加
 * add()方法先对对象进行哈希码的判断，相同在进行equals的判断
 * 对于原先的hashCode()方法进行覆盖，使其可以进行对象的内容进行创建哈希码，既保持对内容不同的对象，哈希码不同；也要进行内容相同时，哈希码相同
 * 对于equals()的覆盖进行内容判断而决定
 * */
public class TestHashSetAdd {
    public static void main(String[] args) {
        Student stu1=new Student("张三",13,"男",99D);
        Student stu2=new Student("伍六一",15,"男",97D);
        Student stu3=new Student("史今",25,"男",91D);
        Student stu4=new Student("许三多",29,"男",94D);
        Student stu5=new Student("张三",13,"男",99D);

        HashSet<Student> set=new HashSet<Student>();
        set.add(stu1);
        set.add(stu2);
        set.add(stu3);
        set.add(stu4);
        set.add(stu5);

        for (Student str :
                set) {
            System.out.println(str);
        }

    }
}
class Student{
    String name;
    Integer age;
    String sex;
    Double score;

    public Student() {
    }

    public Student(String name, Integer age, String sex, Double score) {
        this.name = name;
        this.age = age;
        this.sex = sex;
        this.score = score;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                ", score=" + score +
                '}'+hashCode();
    }

    @Override
    public int hashCode() {
        return this.name.hashCode()+this.age.hashCode()+this.sex.hashCode()+this.score.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        System.out.println("-----Student.equals() Execute----");
        if (this==obj) return true;
        if (obj==null) return false;
        if (this.getClass()!=obj.getClass()) return false;
        Student str=(Student) obj;
        if (this.name.equals(str.name) && this.age.equals(str.age) && this.sex.equals(str.sex) && this.score.equals(str.score))
            return true;
        return false;
    }
}
